<template>
  <div style="padding: 15px;">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="移位单">
              <el-input v-model="form.code" style="width:75%" disabled />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="仓库">
              <el-select v-model="form.warehouseCode" placeholder="请选择" disabled>
                <el-option v-for="item in warehouseList" :key="item.value" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <div class="grid-content bg-purple">
            <el-form-item label="备注" prop="shipmentCode" >
              <el-input v-model="form.remarks" style="width:75%" disabled/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <br>
    <vxe-table
      border
      :keep-source=true
      resizable
      show-overflow
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      :span-method="objectSpanMethod"
      show-footer
      @edit-actived="editActivedEvent"
      auto-resize
      :edit-rules="validRules"
      :edit-config="{trigger: 'click', mode: 'cell'}">
    >
      <vxe-table-column type="seq" width="60" title="序号"></vxe-table-column>
      <vxe-table-column title="入驻商" field="shipmentName" min-width="200" />
      <vxe-table-column field="goodsName" title="商品名称"  width="200"></vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位"  width="100" ></vxe-table-column>
      <vxe-table-column field="moveQuantity" title="移出数量" min-width="80"  />
      <vxe-table-column field="spaceName" title="库区" min-width="200"  />
      <vxe-table-column field="locationName" title="移出库位" min-width="200"  />
      <vxe-table-column field="status" title="移位状态" min-width="120" :formatter="formatStatus"    />
      <vxe-table-column field="movedQuantity" title="移位数量" :edit-render="{name: 'input' ,attrs: {disabled: Disabled}}" width="120"></vxe-table-column>
      <vxe-table-column field="targetLocationName" title="移入库位" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <locationSelect :val1="form.warehouseCode" ref="locationSelect" :val2="Disabled" @setGoodsCode="setLocationCode(row)" />
        </template>
      </vxe-table-column>

      <vxe-table-column field="gmtManufacture" title="生产日期"  width="120"></vxe-table-column>
      <vxe-table-column field="gmtExpire" title="过期日期"  width="120"></vxe-table-column>
      <vxe-table-column field="isLock" title="锁定状态" min-width="200" :formatter="formatIsLock"  />
      <vxe-table-column field="taskCode" title="任务号" min-width="200" />
      <vxe-table-column field="operatorName" title="作业人" min-width="200"  />
      <vxe-table-column field="remarks" title="备注" min-width="200"  />
      <vxe-table-column title="操作" fixed="right" min-width="150">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="拆分" placement="top" v-if="scope.row.isShow == '0'">
            <vxe-button type="text" @click="insertEvent(tableData[scope.row.num + 1],scope.row)">
              <i class="iconfont icon-zhuangchedanguanli" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top" v-if="scope.row.isShow == '1'">
            <vxe-button type="text" @click="remove(scope.row)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>

    </vxe-table>

    <vxe-toolbar/>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSubmit" :disabled="isDisable" plain>提交</el-button>
    </div>

  </div>
</template>

<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
import VXETablePluginElement from 'vxe-table-plugin-element'
import '@/assets/iconfont/iconfont.css';

import 'vxe-table-plugin-element/dist/style.css'
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
VXETable.use(VXETablePluginElement)
import locationSelect from '@/views/components/locationsElSelect.vue'
  import { getWarehouse, } from "@/api/basicInfo";

import { moveConfirm,movePutConfirm } from "@/api/store";
export default {
  name: "moveAudit",
  components: {
    locationSelect,
  },

  data() {
    return {
      message: "",
      loading: false,
      allAlign: "center",
      tableData: [],
      isDisable:false,   //确定键显示按钮
      Disabled: false,
      validRules: {
        movedQuantity: [
          { required: true, message: '移位数量必须填写' },
          { pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d{0,6})$/, message: '小数点后保留六位小数，不能为负' },
        ],
        targetLocationName: [
          { required: true, message: '移入库位必须填写' },
        ],
      },

      code: "",
      start:'0',
      spanArr: [], // 一个空的数组，用于存放每一行记录的合并数
      pos: 0, // spanArr 的索引
      contentSpanArr: [],
      position: 0      ,

      itemListQuery: {
        //移位单号
        // moveCode: this.moveDetail.code,
        pageNum: 1,
        pageSize: 10,
        sortField: "",
        sortType: "",
      },

      warehouseList: [],
      locationList: [],

      modelChooseInventoryFlag: false,

      form: {
        code: '',
        warehouseCode: "",
        warehouseName: "",
        remarks: "",
        moveItemDTOList:[],
        status: 0,
        moveItemVOList: [],
          moveRegisterVOList: [],
      },

      rules:{
        warehouseCode: [
          { required: true, message: "请选择仓库", trigger: "blur" },
        ]
      }
    };
  },

  created() {
    this.findWarehouseList()
    this.getInfo();

  },
  methods: {
      findWarehouseList(){
        getWarehouse().then((response)=>{
          this.warehouseList = response.data;
        })
      },
      editActivedEvent ({ row, rowIndex }) {
        this.Disabled = row.isShow == 10
      },

    // 表格合并行
    objectSpanMethod({ row, rowIndex,column,  columnIndex }) {
      if(this.start == 1){
        if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4
          || columnIndex === 5 || columnIndex === 6  || columnIndex === 7  || columnIndex === 8
          || columnIndex === 12|| columnIndex === 13|| columnIndex === 14|| columnIndex === 15|| columnIndex === 16) {
          const _row = this.spanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          };
        }
      }
    },
    remove(row){
      this.$refs.xTable.remove(row)
      this.tableData = this.$refs.xTable.tableData
      this.tableData.forEach( (i,index) => {
        if(i.num){
          i.num = index
        }
      })
      this.spanArr = [];
      this.contentSpanArr = [];
      for (var i = 0; i < this.tableData.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0;
          this.contentSpanArr.push(1);
          this.position = 0;
        } else {
          // 判断当前元素与上一个元素是否相同(第1和第2列)
          if (this.tableData[i].moveItemCode == this.tableData[i - 1].moveItemCode) {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
          }

        }
      }
    },

    //库位选择
    setLocationCode(row){
      let obj = this.$refs.locationSelect.obj
      row.targetLocationName = obj.serialNumber
      row.targetLocation = obj.code
      row.spaceCode = obj.spaceCode
    },

    insertEvent (row,Row) {
      if(row == undefined){
        row = -1
      }
      // 复制一份，清除掉库区、库位、上架数量
      let record = JSON.parse(JSON.stringify(Row));
      record.targetLocation = '';
      record.targetLocationName = '';
      // record.spaceCode = '';
      record.movedQuantity = '';
      record.isShow = 1;
      record.num = Row.num;
      record.edit = 0
      record.status = '11';

      let { row: newRow } = this.$refs.xTable.insertAt(record, row)
      this.$refs.xTable.setActiveCell(newRow, 'isShow')
      this.tableData = this.$refs.xTable.tableData
      this.tableData.forEach( (i,index) => {
        if(i.num){
          i.num = index
        }
      })
      this.start = 1
      this.spanArr = [];
      this.contentSpanArr = [];
      for (var i = 0; i < this.tableData.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0;
          this.contentSpanArr.push(1);
          this.position = 0;
        } else {
          // 判断当前元素与上一个元素是否相同(第1和第2列)
          if (this.tableData[i].moveItemCode == this.tableData[i - 1].moveItemCode) {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
          }

        }
      }
    },

    // 获取页面信息
    getInfo() {
      this.loading = true
      let code = this.$route.query.code ? this.$route.query.code : "";
        moveConfirm(code).then(response => {
        this.form = response.data,
        this.tableData = this.form.moveRegisterVOList
        for (let i = 0; i < this.tableData.length; i++) {
          this.tableData[i].num = i
        }
        this.tableData.forEach( i => {
          if(i.edit == 1){
            i.isShow = 10
          }else{
            i.isShow = 0
          }
        })
        this.spanArr = [];
        this.contentSpanArr = [];
        for (var i = 0; i < this.tableData.length; i++) {
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
            this.contentSpanArr.push(1);
            this.position = 0;
          } else {
            // 判断当前元素与上一个元素是否相同(第1和第2列)
            if (this.tableData[i].moveItemCode == this.tableData[i - 1].moveItemCode
                ) {
              this.spanArr[this.pos] += 1;
              this.spanArr.push(0);
              this.start = 1
            } else {
              this.spanArr.push(1);
              this.pos = i;
            }

          }
        }

        this.loading = false
      })
    },

    formatStatus({cellValue}){
        console.info(cellValue)
      if(cellValue == '11'){
        return '待移位';
      }
      if(cellValue == '12'){
        return '移位中';
      }
      if(cellValue == '13'){
        return '移位完成';
      }

    },
    formatIsLock({cellValue}){
      if(cellValue == '0'){
        return '否';
      }else{
        return '是'
      }
    },
    // 提交
     funcSubmit() {
        const { tableData } = this
        let len = tableData.length
        for(let i = 0; i < len; i++){
          if(!tableData[i].targetLocationName)return this.$message.error('移入库位不能为空')
          if(tableData[i].movedQuantity === 0 || tableData[i].movedQuantity === '0')return this.$message.error('移入数量不能为0')
          let reg =  /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d{0,6})$/
          if(!reg.test(tableData[i].movedQuantity))return this.$message.error('请检查移入数量')
        }
        this.form.moveRegisterDTOList = this.$refs.xTable.tableData
        const data = this.form
        this.isDisable = true
        movePutConfirm(data).then(response => {
          this.$message({ message: response.msg, type: 'success' })
          this.$emit('fatherAddMethod')
          this.isDisable = false
        }).then(() => {
          this.$eventBus.$emit('refreshList')
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.go(-1);
        }).catch(() => this.isDisable = false)
      }
    },



    footerMethod ({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 1) {
            return '合计'
          }

          if (['totalQuantity'].includes(column.property)) {
              return XEUtils.sum(data, column.property).toFixed(3)
          }
          if (['moveQuantity'].includes(column.property)) {
              return XEUtils.sum(data, column.property).toFixed(3)
          }
          return '-'
        })
      ]
    },

    fucCancel() {
      this.$emit("fatherCancel", "audit");
    },

};
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis),
.vxe-table .vxe-footer--column:not(.col--ellipsis),
.vxe-table .vxe-header--column:not(.col--ellipsis) {
  padding: 6px 0;
}
.vxe-toolbar {
  padding: 0 0 10px 0;
}
</style>
<style lang="scss" scoped >
.dialog-footer {
  margin: 15px auto;
  width: 200px;
}
</style>
